package com.gxuwz.medical.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil11 {
	private static final String driverClass="com.mysql.jdbc.Driver";
	private static final String url="jdbc:mysql://127.0.0.1:3306/medcialdb?useUnicode=true&characterEncoding=utf-8&useSSL=true";
	private static final String user="root";
	private static final String password="123456";
	private Connection conn;
	 /**
	  * 获取数据库连接
	  * @return
	  */
	  public static Connection getConn(){
		  Connection conn =null;
		  try{
			  Class.forName(driverClass);
			  conn =DriverManager.getConnection(url, user, password);
			  System.out.print("连接数据库成功");
		  }catch (Exception e) {
			 e.printStackTrace();
		}
		  
		  return conn;
	  }
	  /**
	   * 
	   * @param sql
	   * @throws SQLException
	   */
	  public static int executeUpdate(String sql,Object...obj)throws SQLException{
		  Connection conn=null;
		  PreparedStatement ps=null;
		  conn=getConn();
		  int c=0;
		  try{
			  ps=conn.prepareStatement(sql);
			  for(int i=0;i<obj.length;i++){
			  ps.setObject(i+1, obj[i]); 
			  }
			  c=ps.executeUpdate();
		  }catch (SQLException e) {
			throw new SQLException(e.getMessage(),e);
		}finally{
			
			close(ps, conn);
			
		}
		  return c;
	  }
	  /**
	   * 
	   * @param sql
	   * @throws SQLException
	   */
	  
	  
	
	  public ResultSet executeQuery(Statement stmt,String sql)throws SQLException{
	
	
		  ResultSet rs=null;
		  try{
			  rs=stmt.executeQuery(sql);
			  return rs;
		  }catch (SQLException e) {
			throw new SQLException("执行SQL查询失败"+e.getMessage(),e);
		}
	  }

	  public static void close(ResultSet rs,Statement stmt,Connection conn)throws SQLException{
		  try{
			  if(rs!=null){
				  rs.close();
				}
			   if(stmt!=null){
					stmt.close();
				}
				if(conn!=null){
					conn.close();
				}
		  }catch (SQLException e) {
			throw new SQLException("关闭数据库连接资源失败!"+e.getMessage(),e);
		}
		  
	  }
	  public static void close(Statement stmt,Connection conn)throws SQLException{
		  close(null, stmt, conn);
	  }
	  /**
	   * 关闭连接
	   * @param conn
	   * @throws SQLException
	   */
	  public static void close(Connection conn)throws SQLException{
		  close(null, null, conn);
	  }
	  
	  /**
	   * 关闭Statement
	   * @param conn
	   * @throws SQLException
	   */
	  public static void close(Statement stmt)throws SQLException{
		  close(null, stmt, null);
	  }
	public static ResultSet executeQuery(PreparedStatement ps) throws SQLException {
		  ResultSet rs=null;
		  try{
			  rs=ps.executeQuery();
			  return rs;
		  }catch (SQLException e) {
			throw new SQLException("SQL"+e.getMessage(),e);
		}
	  }
	}
	 

